import { createRouter, createWebHashHistory } from "vue-router";

import DashboardLayout from "@/layout/DashboardLayout";
import AuthLayout from "@/layout/AuthLayout";

import Dashboard from "../views/Dashboard.vue";
import Icons from "../views/Icons.vue";
import Maps from "../views/Maps.vue";
import Profile from "../views/UserProfile.vue";
import Tables from "../views/Tables.vue";
import Zhoubao from "../views/Zhoubao.vue";

import Login from "../views/Login.vue";
import Register from "../views/Register.vue";

const routes = [
  {
    path: "/",
    redirect: "/dashboard",
    component: DashboardLayout,
    children: [
      {
        path: "/dashboard",
        name: "dashboard",
        meta: { auth: true },
        components: { default: Dashboard },
      },
      {
        path: "/icons",
        name: "icons",
        meta: { auth: true },
        components: { default: Icons },
      },
      {
        path: "/maps",
        name: "maps",
        components: { default: Maps },
      },
      {
        path: "/profile",
        name: "profile",
        components: { default: Profile },
      },
      {
        path: "/tables",
        name: "tables",
        components: { default: Tables },
      },
      {
        path: "/zhoubao",
        name: "周报",
        components: { default: Zhoubao },
      },
    ],
  },
  {
    path: "/",
    redirect: "login",
    component: AuthLayout,
    children: [
      {
        path: "/login",
        name: "login",
        components: { default: Login },
      },
      {
        path: "/register",
        name: "register",
        components: { default: Register },
      },
    ],
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  linkActiveClass: "active",
  routes,
});

//路由守卫
router.beforeEach((to, from, next) => {
  // console.log(to, from);
  if (to.meta.auth) { // 判断该路由是否需要登录权限
    if (localStorage.getItem('user')) { //判断本地是否存在token
      next();
    } else {
      // next({path: '/login'})
      next('/login')
    }
  }
  else {
    next();
  }
  // 如果本地存在token则不允许直接跳转到 登录页面
  if (to.fullPath == "/login") {
    if (localStorage.getItem('user')) {
      next({
        path: from.fullPath
      });
    } else {
      next();
    }
  }
});

export default router;
